#include <pthread.h>
#include <sys/time.h>

#include "network.h"
#include "manager.h"

#define SEND_USECTIME_INTERVAL 16*1000
#define SLEEP_USECTIME_INTERVAL 1*1000
void* sendThreadFunc(void*);
void* acceptThreadFunc(void*);
void* managerUpdateThreadFunc(void*);

pthread_t threadId[3];

Network network;
Manager manager;

int main(int argc, char* argv[])
{
	string str;

	network.init();
	manager.init();

	pthread_create(&threadId[0], NULL, sendThreadFunc, NULL);
	pthread_create(&threadId[1], NULL, acceptThreadFunc, NULL);
	pthread_create(&threadId[2], NULL, managerUpdateThreadFunc, NULL);

	while( manager.getState() != QUIT )
	{
		str = network.recvFromCli();
		if( !str.empty() )
			manager.update(str);


	}
	pthread_join(threadId[0], NULL);
	pthread_join(threadId[1], NULL);
	pthread_join(threadId[2], NULL);

	network.cleanup();
	manager.cleanup();
	return 0;
}

void* sendThreadFunc(void*)
{
	struct timeval time;
	struct timeval preTime;
	struct timezone tz;
	
	gettimeofday(&preTime,&tz);

	while( manager.getState() != QUIT)
	{
		gettimeofday(&time,&tz);

		if( time.tv_sec > preTime.tv_sec || time.tv_usec >= preTime.tv_usec )
		{
			network.sendToCli(manager.getAllPosition());

			preTime.tv_usec = time.tv_usec + SEND_USECTIME_INTERVAL;
			preTime.tv_sec = time.tv_sec;
			if( preTime.tv_usec > 1000000)
			{
				preTime.tv_usec -= 1000000;
				preTime.tv_sec += 1;
			}

		}
		else
			usleep(SLEEP_USECTIME_INTERVAL);

		
	}
	return NULL;
}

void* acceptThreadFunc(void*)
{
	network.acceptFromCli();
	return NULL;
}

void* managerUpdateThreadFunc(void*)
{
	return NULL;
}
